package com.qcby.llmtchstd.controller;

import com.qcby.llmtchstd.dao.ExamPaperDao;
import com.qcby.llmtchstd.entity.Exam;
import com.qcby.llmtchstd.utils.BrowserUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.qcby.llmtchstd.common.ResponseResult;
import com.qcby.llmtchstd.dto.ExamPaperDto;
import com.qcby.llmtchstd.service.ExamPaperService;
import com.qcby.llmtchstd.service.OfficeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 试卷文件控制器（仅负责接收请求和响应，不处理业务逻辑）
 */
@Api(tags = "试卷文件")
@RestController
@RequestMapping("/examPaper")
public class ExamPaperController {

    @Resource
    private OfficeService officeService;
    @Autowired
    private ExamPaperService examPaperService;
    @Autowired
    private ExamPaperDao examPaperDao;

    // 注意：要放在类里、方法外，作为类的成员变量
    private static final Logger logger = LoggerFactory.getLogger(ExamPaperController.class);

    @GetMapping("/downloadWord")
    @ApiOperation(value = "生成并下载试卷Word", notes = "根据试卷ID生成Word文档")
    public void downloadExamPaperWord(
            @ApiParam(value = "试卷ID", required = true, example = "1")
            @RequestParam Long paperId,
            HttpServletResponse response,
            HttpServletRequest request) {

        // 1. 直接查询数据库获取试卷原始信息（绕开DTO可能的问题）
        Exam exam = examPaperDao.selectById(paperId); // 直接用DAO查原始实体
        if (exam == null) {
            try {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "试卷不存在");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }

        // 2. 强制获取试卷名称（直接从数据库实体拿，最可靠）
        String paperName = exam.getExamName();
        // 兜底：如果数据库中名称为空，设置默认值
        if (paperName == null || paperName.trim().isEmpty()) {
            paperName = "试卷_" + paperId; // 用ID作为默认名称
        }
        System.out.println("强制获取的试卷名称：" + paperName); // 确认名称

        // 3. 生成DTO和文档（保持原有逻辑，但文件名用强制获取的）
        ExamPaperDto paperDto = officeService.getExamPaperById(paperId);
        XWPFDocument document = officeService.generateExamPaper(paperDto);

        // 4. 下载时强制使用从数据库获取的名称
        try {
            String fileName = paperName + ".docx"; // 这里直接用数据库中的名称
            String encodedFileName = BrowserUtils.encodeFileName(request, fileName);

            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);
            response.setCharacterEncoding("UTF-8");

            document.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                document.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 修正：使用@RequestParam接收Integer类型的ID（与Service层保持一致）
    @PostMapping("/selectById")  // 推荐使用明确的PostMapping
    @ResponseBody
    @ApiOperation("获取试卷信息")
    public ResponseResult selectById(
            @ApiParam(value = "试卷ID", required = true, example = "1")
            @RequestParam Long id) {  // 改为@RequestParam接收URL参数
        return examPaperService.selectById(id);
    }
}
